package com.testclock.erebus.testbleclock;

import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.MenuAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.clj.fastble.BleManager;
import com.clj.fastble.data.ScanResult;
import com.clj.fastble.scan.ListScanCallback;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    BleManager bleManager;
    ListView listView;
    Button scanButton;
    List<ScanResult> results;
    BaseAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bleManager = ((MyApplication) getApplication()).getBleManager();
        if (!bleManager.isBlueEnable()) {
            bleManager.enableBluetooth();
        }
        initView();

    }

    private void initView() {
        results = new ArrayList<>();
        listView = (ListView) findViewById(R.id.list_view);
        adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return results.size();
            }

            @Override
            public Object getItem(int position) {
                return results.get(position);
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if (convertView == null) {
                    convertView = getLayoutInflater().inflate(
                            R.layout.list_item_view, null);
                }
                TextView name = (TextView) convertView.findViewById(R.id.name);
                TextView mac = (TextView) convertView.findViewById(R.id.mac_addr);
                TextView rssi = (TextView) convertView.findViewById(R.id.rssi);
                ScanResult scanResult = results.get(position);
                rssi.setText(String.valueOf(scanResult.getRssi()));
                name.setText(scanResult.getDevice().getName());
                mac.setText(scanResult.getDevice().getAddress());
                return convertView;
            }
        };
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                bleManager.cancelScan();
                setViewEnable(true);
                Intent intent = new Intent(MainActivity.this, OpenActivity.class);
                Bundle bundle = new Bundle();
                bundle.putParcelable("result", results.get(position));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        scanButton = (Button) findViewById(R.id.scan_btn);
        scanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!bleManager.isBlueEnable()) {
                    bleManager.enableBluetooth();
                } else {
                    scanDevice();
                }
            }
        });
    }

    private void setViewEnable(boolean enable) {
        scanButton.setEnabled(enable);
    }

    private void scanDevice() {
        setViewEnable(false);
        results.clear();
        bleManager.scanDevice(new ListScanCallback(3000) {
            @Override
            public void onScanning(ScanResult result) {
                if (null != result && parseAdvData(result.getRssi(), result.getScanRecord())) {
                    results.add(result);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onScanComplete(ScanResult[] results) {
                setViewEnable(true);
            }
        });
    }

    private boolean parseAdvData(int rssi, byte[] scanRecord) {
        if (rssi < -75) return false;
        byte[] bytes = ParseLeAdvData.adv_report_parse(ParseLeAdvData.BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA, scanRecord);
        if (null == bytes || bytes.length < 2) {
            return false;
        }
        if (bytes[0] == 0x01 && bytes[1] == 0x02) {
            return true;
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        bleManager.closeBluetoothGatt();
    }
}
